define(function (require, exports, module) {
    var angular = require('angular');
    require("pagination");
    require("angular-ui");
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀

    angular.module('ContractDredge', [])
        .controller('contractDredgeCtrl', ['$scope','$location', '$routeParams', '$sce', 'contractCommonService', function ($scope,$location, $routeParams,$sce, contractCommonService) {
            var contractId = $routeParams.id;

            $scope.contractTypeName = $location.search().contractType;
            $scope.contractTypes = {};
            $scope.authAppUseListAll;
            $scope.authAppUseList = [];
            //获取合同类别
            contractCommonService.getContractTypes(function (data) {
                $scope.contractTypes = data;
                $scope.contractTypeCode = $scope.contractTypes[$scope.contractTypeName];
                $scope.$applyAsync();
            });

            $scope.getremark = function(lists){
                listarr = [];
                $.each(lists, function (idx,item) {
                    var isexists = false;
                    var idx = 0;
                    for(i=0;i<listarr.length;i++){
                        if(listarr[i].application_id == item.application_id){
                            idx = i;
                            isexists = true;
                            break;
                        }
                    }
                    if(isexists) {
                        listarr[idx].value = parseFloat(listarr[idx].value) + parseFloat(item.authorization_numeric);
                    }else{
                        var ll = {};
                        ll.application_id = item.application_id;
                        ll.name = item.application_name;
                        ll.authorization_total = 0;
                        ll.value = item.authorization_numeric;
                        ll.isover = '否';
                        listarr.push(ll);
                    }
                });
                var remark = '';
                for(i=0;i<listarr.length;i++){
                    for(j=0;j<$scope.applist.length;j++){
                        if(listarr[i].application_id == $scope.applist[j]['application_id']){
                            listarr[i].authorization_total = $scope.applist[j]['authorization_numeric'];
                            listarr[i].isover = parseFloat(listarr[i].value) >= parseFloat(listarr[i].authorization_total) ? '是' : '否';
                            remark += listarr[i].name + ':' + $scope.applist[j]['authorization_numeric'] + " <font color=blue>(" + listarr[i].value + ")</font> ";
                        }
                    }
                };
                $scope.authorAppList = listarr;
                $scope.payoverremark =$sce.trustAsHtml(remark);
            };

            //获取合同信息
            contractCommonService.getContract(contractId, function (data) {
                $scope.contractBaseInfo = data.contract;
                $scope.tenant = data.tenant;
                $scope.applist = data.application;
                $scope.payovers = data.payover;
                $scope.getremark(data.payover);
                $scope.authAppUseListAll = data.authappuselist;
                $scope.$applyAsync();
            });

            $scope.showAuthorUseInfo = function (authid,appid,appname) {
                $scope.authAppUseList = [];
                $scope.authAppUseListAll.forEach(function(itm,idx){
                    if(itm.product == appid) {
                        if(itm.is_docking === false){
                            util.alert('旧的授权模式没有明细,整个租户已授权数据:' + itm.auth_total.toString());
                            return;
                        }
                        if(itm.details) {
                            var arrItem = [];
                            for(var i=0;i<itm.details.length;i++){
                                if(itm.details[i].auth_id == authid) {
                                    arrItem = [];
                                    arrItem.tenant_name = itm.tenant_name;
                                    arrItem.tenant_code = itm.tenant_code;
                                    arrItem.app_name = appname;
                                    arrItem.project_name = itm.details[i].project_name;
                                    arrItem.authorize_begin_time = itm.details[i].start_date;
                                    arrItem.authorize_end_time = itm.details[i].end_date;
                                    arrItem.authorize_time = itm.details[i].created_on;
                                    $scope.authAppUseList.push(arrItem);
                                }
                            }
                        }
                    }
                })
                $scope.$applyAsync();
            };

            $scope.newPayoverItem = function () {
                addNewRecord();
            };

            $scope.savePayoverSaas = function (item) {
                if(!item.authorize_period){
                    util.alert('租期必须设置!');
                    return;
                }
                var url = api_prefix + 'contract/save-payover-saas';
                var data = {
                    oid: item.contract_payover_id,
                    tenantname: item.tenant_name,
                    tenantcode: item.tenant_code,
                    authorizeperiod: item.authorize_period
                };
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    data: data,
                    success: function (res) {
                        if (res.retCode == "0") {
                            util.alert('保存成功');
                            contractCommonService.getContract(contractId, function (data) {
                                $scope.payovers = data.payover;
                                $scope.$applyAsync();
                            });
                        } else {
                            util.alert(res.errMsg);
                        }
                    },
                    error: function () {
                        util.alert('系统维护，请稍候重试！');
                    }
                });
            };

            $scope.editPayoverSaas = function (item,idx) {
                //先保存原始数据,取消时使用
                item.orginalData = angular.copy(item);
                item.editMode = 2;
            };

            $scope.cancelPayoverSaas = function (item,idx) {
                if (item.editMode == 1) {
                    var items = $scope.payovers;
                    items.splice(idx, 1);
                } else {
                    angular.extend(item, item.orginalData);
                    item.editMode = 0;
                }
            };
            
            $scope.savePayover = function (item) {
                if(!item.application_name || item.application_name==''){
                    util.alert('请填写应用名称!');
                    return;
                }
                if(!item.begin_time){
                    util.alert('请设置开始时间!');
                    return;
                }
                if(!item.end_time){
                    util.alert('请设置截止时间!');
                    return;
                }
                var url = api_prefix + 'contract/save-payover';
                var data = {
                    oid: item.contract_payover_id,
                    contractid: $scope.contractBaseInfo.contract_id,
                    contractcode: $scope.contractBaseInfo.contract_code,
                    applicationname: item.application_name,
                    begintime: item.begin_time,
                    endtime: item.end_time,
                    editmode: item.editMode
                };
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    data: data,
                    success: function (res) {
                        if (res.retCode == "0") {
                            util.alert('保存成功');
                            contractCommonService.getContract(contractId, function (data) {
                                $scope.payovers = data.payover;
                                $scope.$applyAsync();
                            });
                        } else {
                            util.alert(res.errMsg);
                        }
                    },
                    error: function () {
                        util.alert('系统维护，请稍候重试！');
                    }
                });
            };

            $scope.editPayover = function (item,idx) {
                //先保存原始数据,取消时使用
                item.orginalData = angular.copy(item);
                item.editMode = 2;
            };
            
            $scope.cancelPayover = function (item,idx) {
                if (item.editMode == 1) {
                    var items = $scope.payovers;
                    items.splice(idx, 1);
                } else {
                    angular.extend(item, item.orginalData);
                    item.editMode = 0;
                }
            };
            
            $scope.delPayover = function (item,idx) {
                util.confirm('确定要删除此交付信息吗？', {
                    ok: function () {
                        var url = api_prefix + 'contract/delete-payover';
                        var data = {
                            oid: item.contract_payover_id,
                            contractid: $scope.contractBaseInfo.contract_id
                        };
                        $.ajax({
                            url: url,
                            type: 'post',
                            dataType: 'json',
                            data: data,
                            success: function (res) {
                                if (res.retCode == "0") {
                                    util.alert('删除成功');
                                    contractCommonService.getContract(contractId, function (data) {
                                        $scope.payovers = data.payover;
                                        $scope.$applyAsync();
                                    });
                                } else {
                                    util.alert(res.errMsg);
                                }
                            },
                            error: function () {
                                util.alert('系统维护，请稍候重试！');
                            }
                        });
                    }
                });
            }

            var addNewRecord = function () {
                var items = $scope.payovers;
                var applicationname = '';
                var id;
                id = items.length ? items[0].id + 1 : 1;
                if($scope.contractTypeCode == '1'){
                    applicationname = '';
                }else if($scope.contractTypeCode == '2'){
                    applicationname = '开发商线下活动';
                }else if($scope.contractTypeCode == '3'){
                    applicationname = '供应商考察报告';
                }else if($scope.contractTypeCode == '4'){
                    applicationname = '云采购会员';
                }else if($scope.contractTypeCode == '5'){
                    applicationname = '供应商移动工程协同';
                }else if($scope.contractTypeCode == '6'){
                    applicationname = '云采购采宝';
                }else if($scope.contractTypeCode == '7'){
                    applicationname = '供应商线下活动';
                }
                var payoverinfo = {
                    id: id,
                    application_name: applicationname,
                    supplier_name: $scope.contractBaseInfo.supplier_name,
                    begin_time: '',
                    end_time: '',
                    editMode: '1'
                };
                items.unshift(payoverinfo);
            };
        }]);
});